package com.zhanhong.opencvdemo.loader;

import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatDialog;
import android.view.Gravity;
import android.view.WindowManager;

import com.zhanhong.opencvdemo.R;
import com.zhanhong.opencvdemo.utils.ScreenUtils;

import java.util.ArrayList;

public class LoaderDialog {

    private static final int SIZE_SCALE = 8;
    private static final ArrayList<AppCompatDialog> DIALOGS = new ArrayList<>();
    public static final LoaderStyle DEFAULT_LOADER_STYLE = LoaderStyle.BallSpinFadeLoaderIndicator;

    public static void showLoading(Context context, LoaderStyle style) {
        if (context == null) {
            return;
        }
        final AppCompatDialog dialog = new AppCompatDialog(context, R.style.LoaderDialog);
        dialog.setContentView(LoaderCreator.create(dialog.getContext(), style));
        if (dialog.getWindow() != null) {
            WindowManager.LayoutParams layoutParams = dialog.getWindow().getAttributes();
            layoutParams.width = ScreenUtils.getScreenWidth() / SIZE_SCALE;
            layoutParams.height = ScreenUtils.getScreenHeight() / SIZE_SCALE;
            layoutParams.gravity = Gravity.CENTER;
        }
        dialog.setCancelable(false);
        if (DIALOGS.isEmpty()) {
            DIALOGS.add(dialog);
            showDialog(dialog, style);
        } else {
            DIALOGS.add(0, dialog);
            showDialog(DIALOGS.get(DIALOGS.size() - 1), style);
        }
    }

    public static void showLoading(Object object) {
        if (object instanceof Context) {
            showLoading((Context) object, DEFAULT_LOADER_STYLE);
        } else if (object instanceof Fragment) {
            showLoading(((Fragment) object).getContext(), DEFAULT_LOADER_STYLE);
        } else {
            throw new RuntimeException("Dialog context error.");
        }
    }

    public static void stopLoading() {
        if (DIALOGS.isEmpty()) {
            return;
        }
        AppCompatDialog lastDialog = DIALOGS.get(DIALOGS.size() - 1);
        if (DIALOGS.size() > 1) {
            DIALOGS.remove(0);
            showDialog(lastDialog, DEFAULT_LOADER_STYLE);
        } else {
            lastDialog.cancel();
            DIALOGS.remove(lastDialog);
        }
    }

    private static void showDialog(AppCompatDialog dialog, LoaderStyle style) {
        dialog.setContentView(LoaderCreator.create(dialog.getContext(), style));
        dialog.show();
    }

    public static void stopAllLoading() {
        for (AppCompatDialog dialog : DIALOGS) {
            dialog.cancel();
        }
        DIALOGS.clear();
    }

}
